package com.cn.controller;

import com.cn.service.IUserService;
import com.cn.service.Imp.UserServiceImp;
import com.cn.util.TokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("Token")
public class TokenLoginController {
    public  static final long time=3600;//过期时间为1h
    @Autowired
    IUserService userService;
    @Autowired
    TokenUtil tokenUtil;

    /**
     * 第一次登录
     * 传入user对象
     * 登录成功后生成一个Token
     */
    @ResponseBody
    @RequestMapping("/onceLogin")
    public String onceLogin(@RequestParam("UserName") String UserName, String UserPassword) {

        if (userService.login(UserName, UserPassword)) {
            return  tokenUtil.createJWT("1","u"+UserName+"p"+UserPassword,time);
        } else {
            return "fail";
        }
    }
    @ResponseBody
    @RequestMapping("/tokenLogin")
    public String  tokenLogin(String token){
       try{
           String userObj= tokenUtil.parseJWT(token).getSubject();
           String userName=userObj.substring(1,userObj.indexOf("p"));
           String userPassword=userObj.substring(userObj.indexOf("p")+1);
           if (userService.login(userName,userPassword)) {

               return "success";
           } else {

               return "fail";
           }
           //Token过期应该重新颁布令牌
       }catch (ExpiredJwtException e){
           e.printStackTrace();
           return "expired";
       }catch(IllegalArgumentException illegalArgumentException){
           System.out.println("令牌为空");
           return  "null";
        }
    }



}
